package com.sgb.capital.api;


import com.sgb.capital.callback.Constants;
import com.sgb.capital.utils.MLog;
import com.sgb.capital.utils.NetworkAvailableUtils;
import com.sgb.capital.utils.SPreferenceUtil;
import com.sgb.capital.utils.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * Retrofit Interceptor(拦截器) 拦截请求并做相关处理
 */
public class ZInterceptor implements Interceptor {

    private static Map<String, String> commonParams;
    private boolean mIsPcToken = true;

    public ZInterceptor(boolean isPcToken) {
        this.mIsPcToken = isPcToken;
    }

    public ZInterceptor() {
    }

    public synchronized static void setCommonParam(Map<String, String> commonParams) {
        if (commonParams != null) {
            if (ZInterceptor.commonParams != null) {
                ZInterceptor.commonParams.clear();
            } else {
                ZInterceptor.commonParams = new HashMap<>();
            }
            for (String paramKey : commonParams.keySet()) {
                ZInterceptor.commonParams.put(paramKey, commonParams.get(paramKey));
            }
        }
    }

    public synchronized static void updateOrInsertCommonParam(@NonNull String paramKey, @NonNull String paramValue) {
        if (commonParams == null) {
            commonParams = new HashMap<>();
        }
        commonParams.put(paramKey, paramValue);
    }

    @Override
    public synchronized Response intercept(Chain chain) throws IOException {
        if (!NetworkAvailableUtils.isNetworkAvailable(Utils.getContext())) {
            throw new IOException("无网络，请检查网络连接");
        }
        Request request = rebuildRequest(chain.request());
        Response response = chain.proceed(request);
        // 输出返回结果
        try {
            Charset charset;
            charset = Charset.forName("UTF-8");
            ResponseBody responseBody = response.peekBody(Long.MAX_VALUE);
            Reader jsonReader = new InputStreamReader(responseBody.byteStream(), charset);
            BufferedReader reader = new BufferedReader(jsonReader);
            StringBuilder sbJson = new StringBuilder();
            String line = reader.readLine();
            do {
                sbJson.append(line);
                line = reader.readLine();
            } while (line != null);
            MLog.d("api", "response: " + sbJson.toString());
            Utils.sendMsg(Constants.SB_JSON, sbJson.toString());
        } catch (Exception e) {
            e.printStackTrace();
            MLog.e(e.getMessage(), e.toString());
        }
        return response;
    }

    /**
     * 对参数做特殊处理
     *
     * @param request
     * @return
     * @throws IOException
     */
    private Request rebuildRequest(Request request) throws IOException {
        Request newRequest;
        if ("POST".equals(request.method())) {
            newRequest = rebuildPostRequest(request);
        } else if ("GET".equals(request.method())) {
            newRequest = rebuildGetRequest(request);
        } else {
            newRequest = request;
        }
        // TODO: 2021/5/27 0027
        // TODO: 2021/5/27 0027
        // TODO: 2021/5/27 0027
        MLog.d("api", "request Url: 请求方式" + newRequest.method() + "  请求连接Url = " + newRequest.url().toString());
        String resourcePCToken = SPreferenceUtil.getInstance().getSaveStringData(SPreferenceUtil.resourcePCToken, "");
        String resourceAPPToken = SPreferenceUtil.getInstance().getSaveStringData(SPreferenceUtil.resourceAPPToken, "");
        MLog.d("api", "resourcePCToken:\t" + resourcePCToken);
        if (Utils.isEmpty(resourcePCToken)) {
            MLog.d("Capital", "没有获取到PCToken,请在更新用户信息的时候存储最新的PCToken");
        } else {
            MLog.d("Capital", "PCToken:\t\t" + resourcePCToken);
        }
        return newRequest.newBuilder()
                .addHeader("Authorization", "Bearer " + (mIsPcToken ? resourcePCToken : resourceAPPToken))
                .addHeader("platform", "android")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("type", "app-api-java")
                .build();
    }

    /**
     * 可对post请求做特殊处理
     * 比如对某个接口做参数调整和参数替换，或添加公共请求参数
     */
    private Request rebuildPostRequest(Request request) {
        RequestBody originalRequestBody = request.body();
        try {
            MLog.d("api", "request body " + getParamContent(originalRequestBody));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return request.newBuilder().method(request.method(), originalRequestBody).build();
    }

    /**
     * 获取常规post请求参数
     */
    private String getParamContent(RequestBody body) throws IOException {
        Buffer buffer = new Buffer();
        body.writeTo(buffer);
        return buffer.readUtf8();
    }

    /**
     * 对get请求做统一参数处理
     */
    private Request rebuildGetRequest(Request request) {
        if (commonParams == null || commonParams.size() == 0) {
            return request;
        }
        String url = request.url().toString();
        int separatorIndex = url.lastIndexOf("?");
        StringBuilder sb = new StringBuilder(url);
        if (separatorIndex == -1) {
            sb.append("?");
        }
        for (String commonParamKey : commonParams.keySet()) {
            sb.append("&").append(commonParamKey).append("=").append(commonParams.get(commonParamKey));
        }
        Request.Builder requestBuilder = request.newBuilder();
        return requestBuilder.url(sb.toString()).build();
    }
}
